<template>
  <div>
    <!-- 入口文件 -->
    <VFormRender :form-json="formJson"
                 :form-data="formData"
                 :parent-api="parentApi"
                 :option-data="optionData"
                 ref="vFormRef"/>
    <!-- 弹窗配置 -->
    <surgery-patient
        :visible="msgRegisterMarkLayer.hasCallShow && msgRegisterMarkLayer.layerNameKey == 'surgery-patient'"
        :info="msgRegisterMarkLayer.msgWinData">
    </surgery-patient>
  </div>

</template>

<script>
import VFormRender from "@c/public/form-render/index.vue";
import {setRem2} from "@/utils/rem.js";
import {AndroidSDK} from "@/sdk/AndroidSdkService";
import {resetLongToStr} from "@/utils/biz/common/BizUtils";
import {SubjectUtil} from "@/utils/observer/SubjectUtil";
import {SetDateObserverBiz} from "@/utils/biz/common/SetDateObserverBiz";
import LayerComps from "@/components/public/layer/scenes";
import {MarkLayerObserverBiz} from "@/utils/biz/common/MarkLayerObserverBiz";
import {InformationCommonObserverBiz} from "@/utils/biz/information/InformationCommonObserverBiz";
import {UserCommitApi} from "@/api/user_common";

export default {
  name: "InformationScreen",

  props: {
    formJson: {
      widgetList: [],
      formConfig: {
        devType: true
      },
    },
    formConfig: {},
    formData: Object,
    templateInfo: {},
    // 0表示门诊 1 第三方 2 其他
    apiType: {
      type: Number,
      default: 0
    },
    optionData: {},
  },

  components: {
    VFormRender,
    ...LayerComps
  },

  data() {
    return {
      parentApi: this.createParentOptions(),
      deviceInfo: null,
      // 组件缓存
      modelMap: {},
      // 消息
      eventBus: null,

      bizClassMap: {},
      // 三方接口数据
      apiData: {
        // 分组数据
        groupData: [],
        // 请求地址
        reqUrl: '',
        ApiSign: '',
        // 接口请求频次
        refreshNum: 10,
        // 行数
        scrollNumber: 10,
        // 策略KY
        reqKey: '',
        // 是否切屏
        switchState: false,
        // 切屏间隔
        switchTime: 10,
        // 是否配置接口
        apiState: false,
        // 接口类型
        apiType: '1',
        // 数据结构
        dataType: 'array',
        // 当前屏
        currentIndex: -1,
        // 设置数据
        setData: false,
        // 接口扩展参数
        apiParams: {},
        // 后台无感刷新
        backstageRefresh: false,
        method: 'GET'
      },
      // 排班墙索引
      currentDataIndex: -1,
      // 下标是否从0开始
      beginIndex: -1,
      groupSetInterval: null,
      emptyDataInterval: null,
      /**
       * 对内属性
       */
      commonJsonMap: {},
      // 结构
      commonJsonMapArr: {},
      // 星期几
      weekDays: ['weekMon', 'weekTue', 'weekWed', 'weekThur', 'weekFri', 'weekSat', 'weekSun'],
      // 注册标识
      msgRegisterMark: '',
      // 特制消息弹窗配置
      msgRegisterMarkLayer: {
        // 启用弹窗
        hasOpenLayer: false,
        // 启用语音播报
        hasOpenVideo: false,
        // 弹窗组件名称
        layerNameKey: '',
        // 弹窗开启关闭
        hasCallShow: false,
        // 弹窗配置
        msgWinData: {
          data: {},
        }
      }
    };
  },

  mounted() {
    this.setRem();
    // 初始化
    this.init();
  },

  methods: {
    // 安卓报错信息的写入
    handleException(funcName, errType, errMsg) {
      AndroidSDK.writeLog(`${funcName}--${errType}-->${errMsg}`);
    },

    // 安卓正常写入日志
    handleWriteLog(funcName, msgContent) {
      AndroidSDK.writeLog(`${funcName}---->${msgContent}`);
    },

    /**
     * 安卓调用
     * @param obj
     */
    sdkServices(obj) {
      this.handleWriteLog("sdkServices", JSON.stringify(obj));
      try {
        if (obj.bizType && obj.bizType !== "") {
          switch (obj.bizType) {
            case "getDeviceInfoCallBack":
              this.deviceInfo = JSON.parse(resetLongToStr(obj.msgContent));
              this.initAfterGetDeviceInfo();
              break;
            case "webPing":
              AndroidSDK.androidPong();
              break;
            default:
              // 监听设置
              this.eventBus.$emit(obj.bizType, obj.msgContent);
          }
        } else {
          this.handleException("sdkServices", "数据错误", JSON.stringify(obj));
        }
      } catch (e) {
        this.handleException("sdkServices", "解析错误", JSON.stringify(obj));
      }
    },

    /**
     * 安卓调用
     * @param obj
     */
    sdkBizServices(obj) {
      this.handleWriteLog("sdkBizServices", JSON.stringify(obj));
      try {
        if (obj.bizType && obj.bizType !== "") {
          this.eventBus.$emit(obj.bizType, obj.msgContent);
        } else {
          this.handleException("sdkBizServices", "数据错误", JSON.stringify(obj));
        }
      } catch (e) {
        this.handleException("sdkBizServices", "解析错误", JSON.stringify(obj));
      }
    },

    /**
     * 初始化逻辑
     */
    init() {
      // 数据挂载
      parent.window.webSDKServices = this.sdkServices;
      parent.window.webSDKBizServices = this.sdkBizServices;
      AndroidSDK.androidPong();
      // 遍历数据 将模板数据存储到Map缓存中
      this.formJson.widgetList.forEach((item) => {
        this.modelMap[item.categoryType] = item;
      });
      // 设置接口中需要用的参数
      this.setParams();
      // 主题消息 Subject
      this.eventBus = new SubjectUtil();

      //获取终端信息
      AndroidSDK.getDeviceInfo();
    },
    /**
     * 初始化 模板参数
     */
    setParams() {
      // 加载主屏逻辑
      let mainInfo = this.modelMap["infoPublic"];
      if (mainInfo) {
        let configObj = mainInfo.options[mainInfo.options.config];
        // 特制消息标识
        this.msgRegisterMark = configObj.msgRegisterMark || '';
        this.msgRegisterMarkLayer.hasOpenLayer = configObj.hasOpenLayer === true;
        this.msgRegisterMarkLayer.hasOpenVideo = configObj.hasOpenVideo === true;
        this.msgRegisterMarkLayer.layerNameKey = configObj.layerNameKey || '';
        if (mainInfo.screenDataType.indexOf("ApiInfo") > -1) {
          // 接口标识
          this.apiData.reqKey = configObj.ApiType || '';
          // 接口类型
          this.apiData.apiType = configObj.apiType || '1';
          // 接口地址
          this.apiData.reqUrl = configObj.ApiAddress || configObj.Api || '';
          // 接口标识
          this.apiData.ApiSign = configObj.ApiSign || '';
          // 接口请求频次
          this.apiData.refreshNum = configObj.frequencyApi || 0;
          // 行数
          this.apiData.scrollNumber = configObj.patientListTotal || 10;
          // 是否开启切屏
          this.apiData.switchState = configObj.switchState || false;
          // 切屏时间
          this.apiData.switchTime = configObj.switchTime || 10;
          // 数组 或 对象
          this.apiData.dataType = configObj.dataType || 'array';
          // 是否配置接口
          this.apiData.apiState = configObj.dataType || false;
          // 是否主动设置数据
          this.apiData.setData = (false === configObj.setData) ? configObj.setData : true;
          // 是否主屏 表示会执行分组逻辑，然后发送切屏请求
          this.apiData.isMainScreen = configObj.isMainScreen || false;
          // 主屏 code
          this.apiData.isMainScreenCode = configObj.isMainScreenCode || false;
          // 接口参数
          this.apiData.apiParams = configObj.apiParams || {};
          // 是否无感刷新
          this.apiData.backstageRefresh = true === configObj.backstageRefresh || false;
          this.apiData.method = configObj.rqMethod || 'GET'
        }
      }
    },
    /**
     * 获取设备信息后初始化
     */
    initAfterGetDeviceInfo() {
      // 特制消息清理+注册
      this.registerMsg();

      // 加载主屏逻辑
      let mainInfo = this.modelMap["infoPublic"];
      if (mainInfo) {
        let emp = new InformationCommonObserverBiz(this, this.deviceInfo, this.modelMap["infoPublic"]);
        this.eventBus.addObserver(emp);
        emp.init();
      }

      // 特制消息注册
      if (this.msgRegisterMark !== '') {
        let emp = new MarkLayerObserverBiz(this, this.deviceInfo, this.modelMap["infoPublic"]);
        this.eventBus.addObserver(emp);
        emp.init();
      }


      // 头部时间
      if (this.modelMap["header"]) {
        // 头部时间 - 观察者
        let emp = new SetDateObserverBiz(this, this.deviceInfo, this.modelMap["header"]);
        this.eventBus.addObserver(emp);
      }

      // 获取多媒体
      this.getVideoMedias();

    },

    /**
     * 消息注册
     */
    async registerMsg() {
      // 特制消息存在才会注册
      try {
        // 注册消息
        const {code, data} = await UserCommitApi.bindTerminalBusinessFlag({
          terminalId: this.deviceInfo.screenId,
          terminalType: this.deviceInfo.screenType,
          businessFlag: this.msgRegisterMark
        })
      } catch (e) {
        this.handleException('sdkBizServices', '特制消息注册失败 -- registerMsg -- >', JSON.stringify(e.stack));
      }
    },

    /**
     * 适配2k 4k
     */
    setRem() {
      const {resolution} = this.templateInfo;
      if (resolution) {
        // 重新计算尺寸
        setRem2(19.2, resolution.split("*")[0]);
        window.onresize = function () {
          setRem2(19.2, resolution.split("*")[0]);
        };
      }
    },
    createParentOptions() {
      return {
        self: this,
        executeParentMethod(key, data) {
          switch (key) {
            case "writeLog":
              // 内部组件调用 诙谐LOG 日志
              this.self.handleWriteLog('sdkBizServices', '内部组件打印日志 -- >', data || '')
              break
            case "playVideoMedias":
              // 获取视频组件位置 给安卓
              this.self.playVideoMedias(data);
              break;
          }
        },
      };
    },

    /**
     * 获取多媒体
     * @param data
     */
    getVideoMedias(data) {
      try {
        let roomItem = this.modelMap["infoPublic"];
        const formRef = this.$refs.vFormRef;
        if (formRef) {
          this.$refs.vFormRef.executeChildMethod(roomItem?.id, "getVideoMedias", data || {});
        }
      } catch (e) {
        this.handleException("sdkBizServices", "内部组件异常 -- getVideoMedias -- >", JSON.stringify(e.stack));
      }
    },

    /**
     * 获取 多媒体
     * @param obj
     */
    playVideoMedias(obj) {
      try {
        const {positionInfo, video} = obj;
        const {left, top, width, height, time} = positionInfo;
        const resources = [];
        video.forEach((item) => {
          resources.push({
            url: item.url
          });
        });
        AndroidSDK.playVideoMedias({
          x: left,
          y: top,
          width: width,
          height: height,
          type: "2",
          time: time,
          resources
        });
      } catch (e) {
        this.handleException("sdkBizServices", "获取多媒体数据解析失败", JSON.stringify(e.stack));
      }
    },

  }

};
</script>
